#!/usr/bin/python3
import rospy
import tf2_ros
from geometry_msgs.msg import Twist
import math
import tf
import os
import threading
import numpy as np
import time





            
#控制类
class RobotController:
    def __init__(self):

        ####定义常量####
        self.MAX_LINEAR_SPEED =  11             #最大线速度，单位 cm/s
        self.MAX_ANGULAR_SPEED = 20             #最大角速度,单位 度/s

        self.KP_LINEAR_SPEED_POINT = 1        #坐标模式线速度KP
        self.KP_LINEAR_SPEED_DETECT = 0.055      #识别模式线速度KP
        self.KP_ANGULAR_SPEED = 1               #角速度环KP

        self.KP_Z_SPEED = 1
        self.MAX_Z_SPEED = 40

        self.MIN_ERROR_XY_POINT = 2             #坐标模式XY方向允许的最小误差，单位 cm
        self.MIN_ERROR_XY_DETECT = 50         #识别模式XY方向允许的最小误差，单位 像素
        self.MIN_ERROR_YAW = 10                 #YAW上最小角度误差，单位 度、

        ####定义变量####

        #目标变量
        self.targetPointX = 0                   #目标坐标：X，单位 cm
        self.targetPointY = 0                   #目标坐标：Y，单位 cm
        self.targetPointZ = 0                   #目标坐标：Z，单位 cm
        self.targetDetectX = 320                #识别模式X方向目标像素 单位 像素
        self.targetDetectY = 0                #识别模式Y方向目标像素 单位 像素
        self.targetDetectZ = 200                  #识别模式Z方向目标像素 单位 像素
        self.targetYaw = 0                      #目标角度YAW， 单位度
        self.targetNum = 8                      #目标数字
        self.targetHeight = 75                  #目标高度

        #中间变量
        self.distanceXY = 0                     #坐标模式距离目标点距离，单位 cm
        self.errorPointX = 0                    #坐标模式X方向偏差像素值，单位 cm
        self.errorPointY = 0                    #坐标模式Y方向偏差像素值，单位 cm
        self.errorPointZ = 0                    #坐标模式Z方向偏差像素值，单位 cm
        self.errorDetectX = 0                   #识别模式X方向偏差像素值，单位 像素
        self.errorDetectY = 0                   #识别模式Y方向偏差像素值，单位 像素
        self.errorDetectZ = 0                   #识别模式Z方向偏差像素值，单位 像素
        self.actualPositionX = 0                #实际位置x
        self.actualPositionY = 0                #实际位置y  
        self.actualPositionZ = 0                #实际位置z
        self.actualPositionYaw = 0              #实际位置YAW
        self.detectX = 0                        #识别到数字中心X坐标
        self.detectY = 0                        #识别到数字中心Y坐标
        self.detectZ = 0                        #识别到数字中心Z坐标
        self.errorYaw = 0                       #Yaw方向误差值，单位 度
        self.cosTheta = 0                       #目标坐标角度余弦值
        self.sinTheta = 0                       #目标坐标角度正弦值
        self.startTime_Laser = 0                #激光开启时间
        self.presentTime_Laser = 0              #激光当前时间
        self.startTime_Delay = 0                #延时开启时间
        self.presentTime_Delay = 0              #延时当前时间
        self.startTime_Laser = 0                #激光开启时间
        self.presentTime_Laser = 0              #激光当前时间
        self.startTime_Height = 0               #高度变换开启时间
        self.presentTime_Height = 0             #高度变换当前时间
        

        #结果变量
        self.resultLinearSpeedXY = 0            #计算输出XY合速度
        self.resultLinearSpeedX = 0             #计算输出X方向速度
        self.resultLinearSpeedY = 0             #计算输出Y方向速度
        self.resultLinearSpeedZ = 0             #计算输出Z方向速度
        self.resultAngularSpeedYaw = 0          #计算输出Yaw方向角速度
        


        #状态变量
        self.flagMovePoint = 0                  #坐标飞行标志


        

        #初始化ROS节点
        rospy.init_node('control', anonymous=True)
        self.rate = rospy.Rate(50)
        rospy.on_shutdown(self.Shutdown)
        #初始化速度话题发布器
        self.vel_msg = Twist()
        self.pubSpeed = rospy.Publisher('/cmd_vel', Twist, queue_size=10)
        #初始化TF缓存
        self.tf_buffer = tf2_ros.Buffer()
        tf2_ros.TransformListener(self.tf_buffer)
        rospy.loginfo("Listening for TF data...")
    #计算坐标模式速度
    def calculate_point_speed(self):

        
        #计算距离
        self.distanceXY = math.sqrt(self.errorPointX * self.errorPointX + self.errorPointY * self.errorPointY)

        #计算合速度大小
        self.resultLinearSpeedXY = self.KP_LINEAR_SPEED_POINT * self.distanceXY 
        self.resultLinearSpeedXY = max(min(self.resultLinearSpeedXY, self.MAX_LINEAR_SPEED), -self.MAX_LINEAR_SPEED)

        #计算三角函数
        if self.distanceXY != 0:
            self.cosTheta = self.errorPointX / (self.distanceXY)
            self.sinTheta = self.errorPointY / (self.distanceXY)


        #计算输出速度
        self.resultLinearSpeedX = self.resultLinearSpeedXY * self.cosTheta
        self.resultLinearSpeedY = self.resultLinearSpeedXY * self.sinTheta
        self.resultAngularSpeedYaw = self.KP_ANGULAR_SPEED * self.errorYaw

        self.resultLinearSpeedZ = self.KP_Z_SPEED * self.errorPointZ
        
        #速度限幅
        self.resultAngularSpeedYaw = max(min(self.resultAngularSpeedYaw, self.MAX_ANGULAR_SPEED), -self.MAX_ANGULAR_SPEED)
        self.resultLinearSpeedZ = max(min(self.resultLinearSpeedZ, self.MAX_Z_SPEED), -self.MAX_Z_SPEED)
        
    
    #计算识别模式速度
    def calculate_detect_speed(self, ID):
        #计算误差像素
        if (ID == 0):
            self.errorDetectX = -(self.targetDetectX - self.detectX)
        elif (ID == 1):
            self.errorDetectX = (self.targetDetectX - self.detectX)
        #self.errorDetectY = self.targetDetectY - self.detectY
        self.errorDetectZ = (self.targetDetectZ - self.detectZ)
        #计算识别后速度
        self.resultLinearSpeedX = self.errorDetectX * self.KP_LINEAR_SPEED_DETECT
        #self.resultLinearSpeedY = self.errorDetectY * self.KP_LINEAR_SPEED_DETECT
        self.resultLinearSpeedZ = self.errorDetectZ * self.KP_LINEAR_SPEED_DETECT
        #计算限速
        self.resultLinearSpeedX = max(min(self.resultLinearSpeedX, self.MAX_LINEAR_SPEED), -self.MAX_LINEAR_SPEED)
        #self.resultLinearSpeedY = max(min(self.resultLinearSpeedY, self.MAX_LINEAR_SPEED), -self.MAX_LINEAR_SPEED)
        self.resultLinearSpeedZ = max(min(self.resultLinearSpeedZ, self.MAX_LINEAR_SPEED), -self.MAX_LINEAR_SPEED)
    
    def get_targetPosition(self):
        try:
                #transform = self.tf_buffer.lookup_transform('map', 'laser_frame', rospy.Time(0))
                transform = self.tf_buffer.lookup_transform('map', 'base_link', rospy.Time(0))
                # 提取位姿数据
                translation = transform.transform.translation
                rotation = transform.transform.rotation

                # 四元数转换为欧拉角
                _, _, yaw = tf.transformations.euler_from_quaternion(
                                (rotation.x, rotation.y, rotation.z, rotation.w))
                self.actualPositionYaw = yaw * 180 / math.pi

                # 获取当前坐标（单位：cm）
                self.actualPositionX = translation.x * 100
                self.actualPositionY = translation.y * 100
        except tf2_ros.TransformException as e:
                rospy.logwarn("Transform not available: %s", e)

    def pubVel(self):
        #发布速度,Twist中速度单位为m/s
        self.vel_msg.linear.x = self.resultLinearSpeedX * 0.01
        self.vel_msg.linear.y = self.resultLinearSpeedY * 0.01



        self.vel_msg.angular.z = self.resultAngularSpeedYaw * math.pi / 180

        
        self.pubSpeed.publish(self.vel_msg)
    
    def dog_move(self ,x, y, yaw=0):
        self.get_targetPosition()
        self.targetPointX = x
        self.targetPointY = y
        self.targetYaw = yaw
        self.errorPointX = self.targetPointX - self.actualPositionX
        self.errorPointY = self.targetPointY - self.actualPositionY
        self.errorYaw = self.targetYaw - self.actualPositionYaw
        while (not rospy.is_shutdown()):
            rospy.loginfo("flag:%f, x:%f, y:%f, yaw:%f", self.flagMovePoint, self.actualPositionX, self.actualPositionY, self.actualPositionYaw)
            if (self.judge_point()):
                break
            self.get_targetPosition()
            self.targetPointX = x
            self.targetPointY = y
            self.targetYaw = yaw
            self.errorPointX = self.targetPointX - self.actualPositionX
            self.errorPointY = self.targetPointY - self.actualPositionY
            self.errorYaw = self.targetYaw - self.actualPositionYaw
            self.calculate_point_speed()
            self.pubVel()

        self.resultLinearSpeedY = 0
        self.resultLinearSpeedX = 0
        self.resultAngularSpeedYaw = 0
        self.pubVel()
    


    #坐标移动,更改目标坐标点
    #返回为真代表已经到达目的地
    def move(self, x, y, z, yaw=0, ignore_z = 0):
        x_act, y_act, yaw_act = self.actualPositionX, self.actualPositionY, self.actualPositionYaw
        z_act = self.actualPositionZ
        self.targetPointX = x
        self.targetPointY = y
        self.targetPointZ = z
        self.targetYaw = yaw
        self.errorPointX = self.targetPointX - x_act   
        self.errorPointY = self.targetPointY - y_act
        self.errorPointZ = self.targetPointZ - z_act
        self.errorYaw = self.targetYaw - yaw_act
        if ignore_z == 0:
            return (abs(self.errorPointX) <= self.MIN_ERROR_XY_POINT and
                    abs(self.errorPointY) <= self.MIN_ERROR_XY_POINT and
                    abs(self.errorYaw) <= self.MIN_ERROR_YAW and
                    abs(self.errorPointZ) <= self.MIN_ERROR_XY_POINT)
        else:
            return (abs(self.errorPointX) <= self.MIN_ERROR_XY_POINT + 6 and
                abs(self.errorPointY) <= self.MIN_ERROR_XY_POINT + 6 and
                abs(self.errorYaw) <= self.MIN_ERROR_YAW and
                abs(self.errorPointZ) <= 10)
    
            


    #判断是否到达目的地
    def judge_point(self):
        return (abs(self.errorPointX) <= self.MIN_ERROR_XY_POINT and
                abs(self.errorPointY) <= self.MIN_ERROR_XY_POINT and
                abs(self.errorYaw) <= self.MIN_ERROR_YAW)
        
    #判断是否到达识别中心
    def judge_detect(self):
        return (abs(self.errorDetectX) <= self.MIN_ERROR_XY_DETECT)
            



    def Shutdown(self):
        rospy.loginfo("SHUT DOWN")
        self.vel_msg.linear.x = 0
        self.vel_msg.linear.y = 0
        self.vel_msg.linear.z = 0

        self.vel_msg.angular.z = 0
        self.pubSpeed.publish(self.vel_msg)

        





    #控制主程序
    def run(self):

        while not rospy.is_shutdown():
            
            
            
           
#############################################___CONTROL_CODE_BEGIN___###############################################################
            if self.flagMovePoint == 0:
                self.dog_move(100, 0)
                self.flagMovePoint = 1
            elif self.flagMovePoint == 1:
                self.dog_move(100, 100)
                self.flagMovePoint = 2
            elif self.flagMovePoint == 2:
                self.dog_move(0, 100)
                self.flagMovePoint = 3
            elif self.flagMovePoint == 3:
                self.dog_move(0, 0)
                self.flagMovePoint = 4
            elif self.flagMovePoint == 4:
                self.dog_move(100, 100)
                self.flagMovePoint = 5
            elif self.flagMovePoint == 5:
                self.dog_move(0, 0)
                self.flagMovePoint = 6



#############################################___CONTROL_CODE_END___################################################################

                


    
            #打印调试
            # rospy.loginfo("MIN:%d, MAX:%d", self.min_data, self.max_data)
            #rospy.loginfo("Time:%.3f",self.Time)





            
            # rospy.loginfo("Position:x: %.3f, y: %.3f, yaw: %.3f, z:%.3f", self.actualPositionX, self.actualPositionY, self.actualPositionYaw, self.actualPositionZ)
            # rospy.loginfo("Speed:x: %.3f, y: %.3f, yaw: %.3f, z:%.3f", self.resultLinearSpeedX, self.resultLinearSpeedY, self.resultAngularSpeedYaw, self.resultLinearSpeedZ)
            # rospy.loginfo("flag:%d", self.flagMovePoint)
            # rospy.loginfo("detct:%d", self.detect_flag)
            # #rospy.loginfo("DetectNum:%d", self.detectNum)
            # rospy.loginfo("MOD:%d", self.mode)t
            self.rate.sleep()

#主函数
if __name__ == '__main__':
    try:
        controller = RobotController()
        controller.run()
    except rospy.ROSInterruptException:
        pass


